# coding: utf-8

# -------------------------------------------------------------------------------
# Name:         password.py
# Description:  
# Author:       XiangjunZhao
# EMAIL:        2419352654@qq.com
# Date:         2019/11/26 16:08
# -------------------------------------------------------------------------------
from django.conf import settings
from rest_framework import serializers

from apps.BasicAuthService.models import User

__all__ = ['PwdSerializer']


class PwdSerializer(serializers.Serializer):
    id = serializers.UUIDField(required=True)
    old_password = serializers.CharField(label='原始密码', required=True, write_only=True)
    password = serializers.CharField(label='新密码', required=True)

    def validate(self, attrs):
        old_password = attrs.get('old_password')
        if old_password:
            del attrs['old_password']
            if not (isinstance(self.instance, User) and self.instance.check_password(old_password)):
                raise serializers.ValidationError('原始密码不正确')
        return attrs

    def update(self, instance, validated_data):
        password = validated_data.get('password') or settings.DEFAULT_PASSWD
        instance.set_password(raw_password=password)
        instance.save()
        return instance
